package com.company.learnjpa.view;

import com.company.learnjpa.model.entity.Blog;
import com.company.learnjpa.model.repository.BlogRepository;
import com.company.learnjpa.util.Helper;
import jakarta.annotation.PostConstruct;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import org.primefaces.PrimeFaces;

/**
 *
 * @author xiaolei
 */
@Named(value = "editBlogView")
@ViewScoped
public class EditBlogView implements Serializable {

    private Blog blog;
    private List<String> categories;

    @Inject
    private BlogRepository blogRepository;

    /**
     * Creates a new instance of EditBlogView
     */
    public EditBlogView() {
    }

    @PostConstruct
    public void init() {
        blog = (Blog) Helper.getFlashObject("blog");
        categories = blogRepository.getAllCategories();
    }

    public void updateBlog() {
        blog.setPublishTime(new Date());
        blog = blogRepository.update(blog);
        PrimeFaces.current().dialog().closeDynamic(blog);
        if (blog == null) {
            Helper.addErrorMessage("Error", "更新失败");
        } else {
            Helper.addInfoMessage("tips", "更新成功");
        }
    }

    public Blog getBlog() {
        return blog;
    }

    public void setBlog(Blog blog) {
        this.blog = blog;
    }

    public List<String> getCategories() {
        return categories;
    }

    public void setCategories(List<String> categories) {
        this.categories = categories;
    }

}
